package org.lzuploader.gui.listeners.servers;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Shell;
import org.lzuploader.gui.WServers;
import org.lzuploader.gui.helpers.EasyMessageBox;
import org.lzuploader.model.Config;
import org.lzuploader.model.Localization;
import org.lzuploader.model.Server;

/** This class is used when the user wants to add a server to the configuration.
 * 
 * @author Emmanuel Cron
 *
 */
public class AddSelectionListener implements SelectionListener
{
    /** The logger for this class. */
    private static Log log = LogFactory.getLog(AddSelectionListener.class);
    
    /** Localization of this class. */
    private Localization localization = Localization.getInstance();
    
    /** Used when the widget is selected by default.
     * @param e The associated event
     */
    @Override
    public void widgetDefaultSelected(final SelectionEvent e)
    {
        widgetSelected(e);
    }

    /** Used when the user clicked on the widget.
     * @param e The associated event
     */
    @Override
    public void widgetSelected(final SelectionEvent e)
    {
        log.debug("Adding server.");
        
        log.trace("Fetching data.");
        
        Shell wServersShell = null;
        for (int i = 0 ; i < e.display.getShells().length ; i++)
        {
            if (e.display.getShells()[i].getData() instanceof WServers)
            {
                wServersShell = e.display.getShells()[i];
                break;
            }
        }
        
        final WServers servers = (WServers) wServersShell.getData();
        final String name = servers.getNameWidget().getText();
        final String serverAddress = servers.getServerWidget().getText();
        final int port = servers.getPortWidget().getSelection();
        final StringBuffer path = new StringBuffer(servers.getPathWidget().getText());
        final Config config = Config.getInstance();
        
        if (path.charAt(path.length() - 1) != '/')
        {
            path.append("/");
        }
        
        final Server newServer = new Server(name);
        newServer.setAddress(serverAddress);
        newServer.setPort(port);
        newServer.setPath(path.toString());
        
        log.trace("Checking if server parameters aren't already known: " + newServer.toString());
        
        for (Server server : config.getServers().values())
        {
            if (
                server.getAddress().equalsIgnoreCase(serverAddress.toString()) &&
                server.getPath().equalsIgnoreCase(path.toString()) &&
                server.getPort() == port
            )
            {
                EasyMessageBox.info(
                    localization.getString("DIALOG_TITLE_INFO"), 
                    localization.getString("DIALOG_SERVER_ALREADY_SAVED") + " " + server.getId().toString()
                );
                return;
            }
        }
        
        log.trace("Adding server to config.");
        
        config.getServers().put(newServer.getId(), newServer);
        
        log.trace("Saving config to file.");
        
        if (!config.save())
        {
            EasyMessageBox.error(
                localization.getString("DIALOG_TITLE_ERROR"),
                localization.getString("DIALOG_SAVE_FAILED")
            );
        }
        
        // Refresh list
        servers.resetComponents();
    }

}
